<?php

namespace App\Http\Middleware;

use App\Kuafu\Common\Enum\CommonCodeEnum;
use App\Kuafu\Common\Exceptions\CommonException;
use App\Kuafu\Customer\Model\CustomerPlatformModel;
use Closure;
use App\Support\AppletEncrypt;

class AppletAuth
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (config('app.env') != 'dev') {
            //从header获取token值
            $token = $request->header('APPLET-TOKEN');
            if (!$token) {
                throw new CommonException(CommonCodeEnum::ERR_NO_TOKEN);
            }
            //检查token是否是小程序平台生成
            try {
                $decryptData = AppletEncrypt::getInstance()->decryptData($token);
            } catch (\Exception $exception) {
                throw new CommonException(CommonCodeEnum::ERR_TOKEN);
            }
            if ($decryptData['platformId'] != $request->header('platformId')) {
                throw new CommonException(CommonCodeEnum::ERR_PLATFORM);
            }
            //检查token是否失效,如果失效重新登陆
            AppletEncrypt::getInstance()->checkInvalidToken($token);
            //检查token
            AppletEncrypt::getInstance()->checkExpireToken($token);


            $request->setUserResolver(function () use ($decryptData) {
                return CustomerPlatformModel::query()
                                            ->where([
                                                'unionid'    => $decryptData["unionid"],
                                                'platformId' => $decryptData['platformId']
                                            ])
                                            ->first();
            });
        }
        return $next($request);

    }
}
